//app.js
import CommonService from 'service/CommonService.js';
const QQMapWX = require('./libs/qqmap-wx-jssdk.min.js');

App({
  onLaunch: function () {
    const timestamp = Date.parse(new Date());
    // 展示本地存储能力
    const _ = this;
    const commonService = new CommonService();
    commonService.login().then(result=>{
      const token = wx.getStorageSync('token');
      const user = wx.getStorageSync('user');
      const config = wx.getStorageSync('config');
      const productTypes = wx.getStorageSync('productTypes');
      const citys = wx.getStorageSync('citys');
      const setting = wx.getStorageSync('setting');
      _.globalData.token = token;
      _.globalData.user = user;
      _.globalData.config = config;
      _.globalData.productTypes = productTypes;
      _.globalData.citys = citys;
      _.globalData.setting = setting;
      const current = Date.parse(new Date());
      if (_.loginReady) {
        _.loginReady(current - timestamp)
      } else {
        let timeout = 3000 - current + timestamp;
        timeout = timeout > 0 ? timeout : 0;
        setTimeout(function () {
          wx.reLaunch({
            url: '/pages/home/home'
          })
        }, timeout)
      }
    });
    // 城市定位
    var locationMt = function(location) {
      // TODO 暂时没有实现 定位自己的城市，需要引入第三方api
      const qqmapsdk = new QQMapWX({
        key: 'MNNBZ-KLHKW-AT6RW-R3RV6-FJRJ6-WJBYJ'
      });

      // 调用接口
      qqmapsdk.reverseGeocoder({
        location: {
          latitude: location.lat,
          longitude: location.lng
        },
        success: function (res) {
          let name = res.result.ad_info.district;
          name = name ? name : res.result.ad_info.city;
          let detail = { name, id: res.result.ad_info.adcode };
          _.globalData.curCity = detail;
          _.globalData.chooseCity = detail;
        },
        fail: function (res) {
        },
        complete: function (res) {
        }
      });
    }
    //获取当前坐标
    wx.getLocation({
      type: 'wgs84',
      success: function (res) {
        _.globalData.location.lat = res.latitude;
        _.globalData.location.lng = res.longitude;
        locationMt(_.globalData.location);
      }
    })
  },
  globalData: {
    user: {},       //当前用户
    setting: {},
    config:{},      //配置信息
    location:{},    //当前位置坐标
    token: null,
    chooseCity:{},  //选择城市
    curCity: {},    //当前城市
    dingwei:{},
    citys: [],
    productTypes: []
  }
})